package com.sc.security.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author sc
 * Created on  2018/1/17
 *
 * 短信验证配置
 */
@Configuration
public class SmsCodeAuthSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain,HttpSecurity> {

    @Autowired
    private AuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private AuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        SmsAuthFilter smsAuthFilter = new SmsAuthFilter();
        smsAuthFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        smsAuthFilter.setAuthenticationSuccessHandler(authenticationSuccessHandler);
        smsAuthFilter.setAuthenticationFailureHandler(authenticationFailureHandler);

        SmsCodeAuthProvider smsCodeAuthProvider = new SmsCodeAuthProvider();
        smsCodeAuthProvider.setUserDetailsService(userDetailsService);
        http.authenticationProvider(smsCodeAuthProvider)
                .addFilterAfter(smsAuthFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
